<template>
  <div class="app-container">
    <div style="display: flex; justify-content: center; align-items: center; margin-top: 10px">
      <div class="selectors row">
        <div class="selectcell row">
          <label>机房：</label>
          <el-select v-model="selectRules.propRoom" placeholder="请选择" style="width: 120px">
            <el-option
              v-for="item in roomOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="selectcell row">
          <label>日期：</label>
          <div class="block">
            <span class="demonstration" />
            <el-date-picker
              v-model="selectRules.propDate"
              style="width: 140px;"
              type="date"
              placeholder="全部日期"
            />
          </div>
        </div>
        <div class="selectcell row">
          <label>类型：</label>
          <el-select v-model="selectRules.propType" placeholder="请选择" style="width: 120px">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="selectcell row">
          <label>状态：</label>
          <el-select v-model="selectRules.propState" placeholder="请选择" style="width: 120px">
            <el-option
              v-for="item in stateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <el-button class="selectcell " @click="resetRules">重置</el-button>
        <el-button type="primary" class="selectcell " @click="query">查询</el-button>
        <el-button icon="el-icon-plus" type="primary" class="selectcell " @click="handleAdd()">添加失物</el-button>
      </div>
    </div>
    <el-row>
      <el-card>
        <el-row class="text-right m-b">
          <!-- <el-input v-model="search" placeholder="输入关键字搜索" style="width: 400px;" /> -->
          <el-table :data="tableData" style="width: 100%" stripe="true" maxheight="100">
            <!-- label是显示的标签，prob是对应data当中的名称，每一个对象当中都应该包含prop -->
            <el-table-column label="序号" align="center" type="index" :index="indexMethod" width="50%" prop="propId" />
            <!-- 失物名称 -->
            <el-table-column label="失物名称" prop="propName" align="center">
              <template slot-scope="{row}">
                <span>{{ row.propName }}</span>
              </template>
            </el-table-column>
            <!-- 失物图片 -->
            <el-table-column label="失物图片" prop="propPictureUrl" align="center" fit="cover">
              <template slot-scope="{row}">
                <img :src="row.propPictureUrl" class="prop_pic">
              </template>
            </el-table-column>
            <!-- 失物描述 -->
            <el-table-column label="失物描述" prop="propDescribe" align="center">
              <template slot-scope="{row}">
                <span class="limited-lines">{{ row.propDescribe }}</span>
              </template>
            </el-table-column>
            <!-- 丢失时间 -->
            <el-table-column label="丢失时间" prop="propDate" align="center">
              <template slot-scope="{row}">
                <span>{{ row.propDate }}</span>
              </template>
            </el-table-column>
            <!-- 失物类型 -->
            <el-table-column label="失物类型" prop="propType" align="center">
              <template slot-scope="{row}">
                <span>{{ typeMap[row.propType] }}</span>
              </template>
            </el-table-column>
            <!-- 丢失地点 -->
            <el-table-column label="丢失地点" prop="propRoom" align="center">
              <template slot-scope="{row}">
                <span>{{ row.propRoom }}</span>
              </template>
            </el-table-column>
            <!-- 状态 -->
            <el-table-column
              class-name="status-col"
              label="状态"
              width="110"
              align="center"
            >
              <template slot-scope="scope">
                <el-tag :type="scope.row.propState | statusFilter">{{
                  scope.row.propState
                }}</el-tag>
              </template>
            </el-table-column>
            <!-- 操作 -->
            <el-table-column align="center" label="操作" width="250%">
              <template slot-scope="scope">
                <el-button size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.row.propId)">删除</el-button>
                <el-button size="mini" type="primary" @click="handleclaim(scope.row)">申领</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-card>
    </el-row>
    <!-- 编辑失物的弹窗显示 -->
    <el-dialog :visible.sync="dialogEditFormVisible">
      <el-form ref="tempTableData" :model="tempTableData" :rules="rules" label-position="center" label-width="90px">
        <!-- 失物名称 -->
        <el-form-item label="失物名称" prop="propName">
          <el-input v-model="tempTableData.propName" />
        </el-form-item>
        <!-- 失物描述 -->
        <el-form-item label="失物描述" prop="propDescribe">
          <el-input v-model="tempTableData.propDescribe" />
        </el-form-item>
        <!-- 丢失时间 -->
        <el-form-item label="丢失时间" prop="propDate">
          <el-col :span="11">
            <el-date-picker v-model="tempTableData.propDate" type="datetime" placeholder="请选择领取日期" style="width: 100%;" />
          </el-col>
        </el-form-item>
        <!-- 丢失时段 -->
        <!-- <el-form-item label="丢失时段" prop="propPeriod">
          <el-select v-model="tempTableData.propPeriod" placeholder="请选择" style="width: 120px">
            <el-option
              v-for="item in periodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
        <!-- 失物类型 -->
        <el-form-item label="失物类型" prop="propType">
          <el-select v-model="tempTableData.propType" placeholder="请选择" style="width: 120px">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 丢失地点 -->
        <el-form-item label="丢失地点" prop="propRoom">
          <el-select v-model="tempTableData.propRoom" placeholder="请选择" style="width: 120px">
            <el-option
              v-for="item in roomOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 状态 -->
        <el-form-item label="状态" prop="propState">
          <el-radio v-model="tempTableData.propState" label="已申领">已申领</el-radio>
          <el-radio v-model="tempTableData.propState" label="未申领">未申领</el-radio>
        </el-form-item>
        <!-- 失物图片 -->
        <el-form-item label="失物图片" prop="propPictureUrl">
          <img :src="tempTableData.propPictureUrl" style="max-width: 100px; max-height: 100px;">
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleAction()">取消</el-button>
        <el-button type="primary" @click="createData()">确定</el-button>
      </div>
    </el-dialog>
    <!-- 新增物品的弹窗显示 -->
    <el-dialog :visible.sync="dialogAddFormVisible">
      <el-form ref="tempTableData" :model="tempTableData" :rules="rules" label-position="center" label-width="90px">
        <el-form-item label="失物名称" prop="propName">
          <el-input v-model="tempTableData.propName" />
        </el-form-item>
        <el-form-item label="失物描述" prop="propDescribe">
          <el-input v-model="tempTableData.propDescribe" />
        </el-form-item>
        <!-- <el-form-item label="丢失时间" prop="propDate">
          <el-col :span="11">
            <el-date-picker v-model="tempTableData.propDate" type="datetime" placeholder="请选择丢失日期" style="width: 100%;" />
          </el-col>
        </el-form-item> -->
        <el-form-item label="丢失地点" prop="propRoom">
          <el-select v-model="tempTableData.propRoom" placeholder="请选择" style="width: 120px">
            <el-option
              v-for="item in addRoomOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="失物类型" prop="propType">
          <el-select v-model="tempTableData.propType" placeholder="请选择" style="width: 120px">
            <el-option
              v-for="item in addTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="propState">
          <el-radio v-model="tempTableData.propState" label="已申领">已申领</el-radio>
          <el-radio v-model="tempTableData.propState" label="未申领">未申领</el-radio>
        </el-form-item>
        <el-form-item label="上传图片" prop="propPictureUrl">
          <el-upload
            class="upload-demo"
            action="localhost:8080"
            :on-change="uploadcheck"
            :file-list="propImage"
            :auto-upload="false"
            :limit="1"
            list-type="picture-card"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleAction()">取消</el-button>
        <el-button type="primary" @click="addData()">确定</el-button>
      </div>
    </el-dialog>
    <!-- 申领的弹窗显示 -->
    <el-dialog :visible.sync="dialogclaimVisible">
      <el-form ref="table" :model="table" :rules="claimrules" label-position="center" label-width="90px">
        <el-form-item label="物品名称" prop="propName">
          <el-input v-model="table.propName" disabled="true" />
        </el-form-item>
        <el-form-item label="学生学号" prop="studentId">
          <el-input v-model="table.studentId" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleAction()">取消</el-button>
        <el-button type="primary" @click="afirmclaim()">确定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      style="margin-top: 10px"
      class="switch"
      background
      :page-size="9"
      layout="prev, pager, next"
      :total="total"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />
  </div>
</template>

<script>
import { addlost, claim, deleteProp, updatelost, uploadPic } from '@/api/lostManage'
import { getLostItem, getRoomNames } from '@/api/lostfound'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        已申领: 'success',
        未申领: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableData: [],
      selectRules: {
        propState: '',
        propDate: '',
        propRoom: '',
        propType: ''
      },
      roomOptions: [],
      addRoomOptions: [],
      stateOptions: [{
        label: '全部',
        value: ''
      }, {
        label: '已申领',
        value: '已申领'
      }, {
        label: '未申领',
        value: '未申领'
      }],
      typeOptions: [{
        label: '全部',
        value: ''
      }, {
        label: '生活用品',
        value: 'DAILY'
      }, {
        label: '学习用品',
        value: 'STUDY'
      }, {
        label: '办公用品',
        value: 'OFFICE'
      }, {
        label: '其他',
        value: 'OTHER'
      }],
      addTypeOptions: [{
        label: '生活用品',
        value: 'DAILY'
      }, {
        label: '学习用品',
        value: 'STUDY'
      }, {
        label: '办公用品',
        value: 'OFFICE'
      }, {
        label: '其他',
        value: 'OTHER'
      }],
      typeMap: {
        'DAILY': '钥匙',
        'STUDY': '学习用品',
        'OFFICE': '办公用品',
        'OTHER': '其他'
      },
      table: [{
        propId: '',
        propName: '',
        studentId: ''
      }],
      tempTableData: [{
        propId: '',
        propName: '',
        propDescribe: '',
        propPictureUrl: '',
        propState: '',
        propDate: '',
        propRoom: '',
        propType: ''
      }],
      propImage: [],
      search: '',
      dialogclaimVisible: false,
      dialogEditFormVisible: false,
      dialogAddFormVisible: false,
      rules: {
        propName: [{ required: true, message: '请输入失物名称', trigger: 'blur' }],
        propDescribe: [{ required: true, message: '请选择失物描述', trigger: 'change' }],
        propState: [{ required: true, message: '请选择失物状态', trigger: 'blur' }],
        propDate: [{ required: true, message: '请选择丢失时间', trigger: 'blur' }],
        propRoom: [{ required: true, message: '请选择丢失地点', trigger: 'blur' }],
        // propPeriod: [{ required: true, message: '请选择丢失时段', trigger: 'blur' }],
        propType: [{ required: true, message: '请选择失物类型', trigger: 'blur' }],
        propPictureUrl: [{ required: true, message: '请上传图片', trigger: 'blur' }]
      },
      claimrules: {
        propName: [{ required: true, message: '请输入失物名称', trigger: 'blur' }],
        studentId: [{ required: true, message: '请输入学生ID', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.created()
  },
  methods: {
    created() {
      this.updateItems(1)
      getRoomNames().then(res => {
        this.roomOptions.push({
          value: '',
          label: '全部'
        })
        for (const item of res.data) {
          this.addRoomOptions.push({
            value: item,
            label: item
          })
          this.roomOptions.push({
            value: item,
            label: item
          })
        }
      })
    },
    handlePageChange(newPage) {
      this.currentPage = newPage
      this.updateItems(this.currentPage)
    },
    query() {
      this.updateItems(1)
    },
    resetRules() {
      this.selectRules.propState = ''
      this.selectRules.propRoom = ''
      this.selectRules.propDate = ''
      this.selectRules.propType = ''
      this.selectRules.propPeriod = ''
      this.updateItems(1)
    },
    updateItems(pageNumber) {
      console.log(pageNumber)
      this.selectRules.propDate = Number(this.selectRules.propDate)
      getLostItem(pageNumber, this.selectRules).then(res => {
        console.log(res.data.propList)
        this.tableData = res.data.propList
        console.log("获取到的图片地址是：", this.tableData)
        this.total = res.data.total
        console.log(typeof this.tableData[0].propDate)
      }).catch(res => {
        console.log(res)
      }).finally(() => {
        if (this.selectRules.propDate === 0) {
          this.selectRules.propDate = ''
        }
      })
    },
    handleclaim(row) {
      if (row.propState === '已申领') {
        alert('该物品已被申领')
      } else {
        this.table.propId = row.propId
        this.table.propName = row.propName
        this.dialogclaimVisible = true
      }
    },
    afirmclaim() {
      this.$refs['table'].validate((valid) => {
        if (valid) {
          this.$confirm('是否确认要申领该物品？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log(this.table.studentId)
            console.log(this.table.propId)
            claim(this.table.studentId, this.table.propId)
              .then((res) => {
                console.log(res.data)
                this.$message({
                  type: 'success',
                  message: '申领成功!'
                })
                this.cancleAction()
              })
              .catch(error => {
                console.error('Error updating materials:', error)
                this.$message({
                  showClose: true,
                  message: '申领失败，请重试！',
                  type: 'error'
                })
              })
          })
        } else {
          this.$message({
            showClose: true,
            message: '请检查信息是否填写完整！',
            type: 'error'
          })
        }
      })
    },
    handleChange(value) {
      console.log(value)
    },
    handleEdit(row) {
      this.tempTableData = Object.assign({}, row)
      this.tempTableData.propId = row.propId
      this.tempTableData.propName = row.propName
      this.tempTableData.propDescribe = row.propDescribe
      this.tempTableData.propDate = row.propDate
      this.tempTableData.propPeriod = row.propPeriod
      this.tempTableData.propType = row.propType
      this.tempTableData.propRoom = row.propRoom
      this.tempTableData.propState = row.propState
      this.tempTableData.propPictureUrl = row.propPictureUrl
      this.dialogEditFormVisible = true
    },
    // 现在想要实现的效果是，更新完数据之后，数据要能够直接显示在原表单里。
    createData() {
      this.$refs['tempTableData'].validate((valid) => {
        if (valid) {
          const index = this.tableData.findIndex(item => item.propId === this.tempTableData.propId)
          console.log(index)
          if (index !== -1) {
            updatelost({
              propId: this.tempTableData.propId,
              propName: this.tempTableData.propName,
              propDescribe: this.tempTableData.propDescribe,
              propState: this.tempTableData.propState,
              propDate: this.tempTableData.propDate,
              propRoom: this.tempTableData.propRoom,
              propType: this.tempTableData.propType,
              // propPeriod: this.tempTableData.propPeriod,
              propPictureUrl: this.tempTableData.propPictureUrl
            })
              .then(res => {
                console.log(res.data)
                this.created()
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
                this.cancleAction()
              })
              .catch(error => {
                console.error('Error updating materials:', error)
                this.$message({
                  showClose: true,
                  message: '修改失败，请重试！',
                  type: 'error'
                })
              })
          }
        } else {
          this.$message({
            showClose: true,
            message: '请检查信息是否填写完整！',
            type: 'error'
          })
        }
      })
    },
    cancleAction() {
      this.dialogclaimVisible = false
      this.dialogAddFormVisible = false
      this.dialogEditFormVisible = false
      this.table = [{
        propId: '',
        propName: '',
        studentId: ''
      }]
      this.tempTableData = [{
        propId: '',
        propName: '',
        propDescribe: '',
        propPictureUrl: '',
        propState: '',
        propDate: '',
        propRoom: ''
      }]
    },
    handleDelete(propId) {
      console.log(typeof propId, '删除失物id')
      this.$confirm('此操作将永久删除此失物记录，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProp(propId).then(() => {
          this.updateItems(this.currentPage)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      }
      )
    },
    // 设置ID号
    indexMethod(index) {
      return index + 1
    },
    handleAdd() {
      this.tempTableData = {
        propId: '',
        propName: '',
        propDescribe: '',
        propPictureUrl: '',
        propState: '未申领',
        propDate: '',
        propRoom: '',
        propPeriod: '',
        propType: ''
      }
      this.dialogAddFormVisible = true
    },
    addData() {
      this.$refs['tempTableData'].validate((valid) => {
        if (valid) {
          this.$confirm('确认要添加此物品？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.tempTableData.propDate = new Date().getTime()
            addlost({
              propName: this.tempTableData.propName,
              propDescribe: this.tempTableData.propDescribe,
              propState: this.tempTableData.propState,
              propDate: this.tempTableData.propDate,
              propRoom: this.tempTableData.propRoom,
              propType: this.tempTableData.propType,
              // propPeriod: this.tempTableData.propPeriod,
              propPictureUrl: this.tempTableData.propPictureUrl
            })
              .then(res => {
                console.log(res.data)
                this.$message({
                  type: 'success',
                  message: '增加成功!'
                })
                this.updateItems(1)
                this.cancleAction()
              })
              .catch(error => {
                console.error(error)
                this.$message({
                  showClose: true,
                  message: '增加失败，请重试！',
                  type: 'error'
                })
              })
          })
        } else {
          this.$message({
            showClose: true,
            message: '请检查信息是否填写完整！',
            type: 'error'
          })
        }
      })
    },
    uploadcheck(file) {
      this.tempTableData.propPictureUrl = ''
      const formData = new FormData()
      formData.append('file', file.raw)
      uploadPic(formData).then(res => {
        console.log(res)
        this.tempTableData.propPictureUrl = res.data
      })
    }
  }

}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;
}

.selectcell{
  display: flex;
  align-items: center;
  margin-left: 20px;
  margin-bottom: 10px;
}

.prop_pic{
  width: 144px;
  height: 80px;
}

.row{
  display: flex;
  flex-direction: row;
}

.limited-lines {
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制在3行内 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 显示省略号 */
  -webkit-box-orient: vertical; /* 设置方向为垂直 */
  line-height: 1.5; /* 行高，可以根据需要调整 */
}

</style>
